package hibatis;

import java.util.regex.Pattern;

/**
 * Created by huangdachao on 2018/6/15 15:00.
 */
public enum FilterType {
    /**
     * =
     */
    eq,

    /**
     * !=
     */
    ne,

    /**
     * >
     */
    gt,

    /**
     * <
     */
    lt,

    /**
     * >=
     */
    goe,

    /**
     * <=
     */
    loe,

    /**
     * 前缀匹配
     */
    preMatch,

    /**
     * 后缀匹配
     */
    postMatch,

    /**
     * 模糊匹配
     */
    fuzzyMatch,

    /**
     * in
     */
    in,

    /**
     * not in
     */
    notIn,

    /**
     * is null
     */
    isNull,

    /**
     * is not null
     */
    notNull;

    public static final Pattern FIELD_PATTERN = Pattern.compile("^[a-zA-Z_][a-zA-Z0-9_]*(.[a-zA-Z_][a-zA-Z0-9_]*)*$");

    public String toSql(String placeholder, Object val) {
        String field = placeholder;
        if (FIELD_PATTERN.matcher(placeholder).find()) {
            placeholder = "#{" + placeholder + "}";
        }
        switch (this) {
            case eq:
                return "=" + placeholder;
            case ne:
                return "!=" + placeholder;
            case gt:
                return "<![CDATA[>]]>" + placeholder;
            case lt:
                return "<![CDATA[<]]>" + placeholder;
            case goe:
                return "<![CDATA[>=]]>" + placeholder;
            case loe:
                return "<![CDATA[<=]]>" + placeholder;
            case preMatch:
                return " like concat(" + placeholder + ", '%')";
            case postMatch:
                return " like concat('%', " + placeholder + ")";
            case fuzzyMatch:
                return " like concat('%', " + placeholder + ", '%')";
            case in:
                if (placeholder.startsWith("(")) {
                    return " in " + placeholder;
                }
                return " in (<foreach item='i' collection='" + field + "' separator=','>#{i}</foreach>)";
            case notIn:
                if (placeholder.startsWith("(")) {
                    return " not in " + placeholder;
                }
                return " not in (<foreach item='i' collection='" + field + "' separator=','>#{i}</foreach>)";
            case isNull:
                if (val == Boolean.TRUE) {
                    return " is null";
                } else {
                    return " is not null";
                }
            case notNull:
                if (val == Boolean.FALSE) {
                    return " is null";
                } else {
                    return " is not null";
                }
            default:
                return "";
        }
    }
}
